package org.argeproje.resim.ui.rcp;

import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import groovy.util.GroovyScriptEngine;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;

import org.apache.bsf.BSFException;
import org.apache.bsf.BSFManager;
import org.codehaus.groovy.bsf.CachingGroovyEngine;
import org.codehaus.groovy.bsf.GroovyEngine;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IOConsole;
import org.eclipse.ui.console.IOConsoleInputStream;
import org.eclipse.ui.console.IOConsoleOutputStream;
import org.eclipse.ui.console.PatternMatchEvent;
import org.eclipse.ui.console.TextConsole;
//import org.unice.javascool.ui.console.input.Input;
import org.eclipse.ui.console.IPatternMatchListener;

public class Console extends IOConsole{

	public final static String ID = "javaSchool.Console";
	private InputStream input=null;

	/**
	 * Some useful colors.
	 */
	private static final Color RED;
	private static final Color BLUE;
	static {
		Display device = Display.getCurrent();
		RED = new Color(device, 255, 0, 0);
		BLUE = new Color(device, 0, 0, 128);
	}
	
	public void showConsole(IConsole console)
	{
		ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[]{ console });
		ConsolePlugin.getDefault().getConsoleManager().showConsoleView(console);		
	}

	public Console(String title) {
		super(title, null);

		IOConsoleOutputStream out = newOutputStream(); 
		out.setColor(BLUE);
		System.setOut(new PrintStream(out));

		IOConsoleOutputStream err = newOutputStream(); 
		err.setColor(RED);
		System.setErr(new PrintStream(err));
		
		input = getInputStream();
		System.setIn(input);
		
		ConsoleJob cj = new ConsoleJob("test",this);
		cj.schedule();
	}
}

class ConsoleJob extends Job
{
	private Console _console;
	
	public ConsoleJob(String name,Console console) {
		super(name);
		_console = console;
	}

	@Override
	protected IStatus run(IProgressMonitor arg0) {
		_console.showConsole(_console);
		
		BufferedReader in = new BufferedReader(new InputStreamReader(_console.getInputStream()));
		String input="";		
		try {
			/*
			BSFManager bsfManager = new BSFManager();
			BSFManager.registerScriptingEngine("groovy",
					"org.codehaus.groovy.bsf.GroovyEngine",
					new String [] {"groovy","gy"});
			//bsfManager.setClassLoader(Thread.currentThread().getContextClassLoader());
			 * *
			*/
			GroovyScriptEngine gse = new GroovyScriptEngine("");
			while(true)
			{
				System.out.print("groovy>");
				System.out.flush();
				input = in.readLine();
				if(input==null)  break;
				else {					
					//Object result = bsfManager.eval("groovy", "input.groovy", 0, 0, input);
					//gse.
					//System.out.println(" " + result);
					System.out.flush();
				}
			}
		} catch (IOException e) {			
			e.printStackTrace();
			System.out.println(e.getMessage());
			return Status.CANCEL_STATUS;
		} 
		System.out.println();
		return Status.OK_STATUS;
	}	
	
	private Object evaluateScript(String script)
	{
		//Binding binding = new Binding(BeanUtils.getParametersAsString(request));		
		//Object value = _gShell.evaluate(script);
		//return value;
		return null;
	}
}


/*
import java.io.InputStream;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.log4j.WriterAppender;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;


public class Console extends MessageConsole {

	private static Map<String, Console> consoles = new HashMap<String, Console>();

	private DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

	private static final Color RED;
	private static final Color BLUE;
	//private static final Color GREEN;
	private static final Color GRAY;
	private static final Color BLACK;

	static {
		Display device = Display.getCurrent();
		RED = new Color(device, 255, 0, 0);
		BLUE = new Color(device, 0, 0, 128);
		//GREEN = new Color(device, 180, 255, 180);
		GRAY = new Color(device, 120, 120, 120);
		BLACK = new Color(device, 0, 0, 0);
	}

	public static boolean debug = false;
	
	//
	// -- CONSTRUCTORS -----------------------------------------------
	//

	public Console(String title) {
		super(title, null);
		activate();	
		
		// Add the standard output and standard error output stream to the Console.
		MessageConsole console = new MessageConsole("System output", null);
		
		ConsolePlugin.getDefault().getConsoleManager().showConsoleView(
		console);
		
		MessageConsoleStream stream = console.newMessageStream();
		System.setOut(new PrintStream(stream));
		System.setErr(new PrintStream(stream));
		System.setIn(new InputStream())

		//----- Log4j Console ------
		// log4j output in the console
		//MessageConsole log4jConsole = new MessageConsole("log4j", null);
		
		//MessageConsoleStream log4jStream = log4jConsole.newMessageStream();
		
		//Logger logger = ProActiveLogger.getLogger(Loggers.CORE);
		//WriterAppender app = new WriterAppender(new SimpleLayout(), log4jStream);
		//logger.addAppender(app);
	
		//ConsolePlugin.getDefault().getConsoleManager().addConsoles(
		//		new IConsole[] {  log4jConsole });
		//-------------------------
		
		ConsolePlugin.getDefault().getConsoleManager().addConsoles(
				new IConsole[]{ this });
	}

	//
	// -- PUBLICS METHODS -----------------------------------------------
	//

	public static synchronized Console getInstance(String title){
		Console console = (Console) consoles.get(title);
		if( console == null){
			console = new Console(title);
			consoles.put(title, console);
		}
		return console;
	}

	public synchronized void log(String message){
		final String text = message;

		printTime();

		// Print the message in the UI Thread in async mode
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				MessageConsoleStream stream = newMessageStream();
				stream.setColor(Console.BLUE);
				stream.println(text);
			}});
	}


	public synchronized void warn(String message){
		final String text = message;

		printTime();

		// Print the message in the UI Thread in async mode
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				MessageConsoleStream stream = newMessageStream();
				stream.setColor(Console.RED);
				stream.println(text);
			}});
	}

	public synchronized void err(String message){
		final String text = message;

		printTime();

		// Print the message in the UI Thread in async mode
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				MessageConsoleStream stream = newMessageStream();
				stream.setColor(Console.GRAY);
				stream.println(text);
			}});
	}

	public synchronized void logException(Throwable e) {
		printTime();
		logExceptionWhithoutTime(e, false);
		e.printStackTrace();
	}

	
	public synchronized void debug(String message) {
		if(debug)
			log(message);
	}
	
	public synchronized void debug(Throwable e) {
		if(debug)
			logException(e);
	}
	
	//
	// -- PRIVATE METHODS -----------------------------------------------
	//

	public void printTime(){
		// Print the message in the UI Thread in async mode
		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				MessageConsoleStream stream = newMessageStream();
				stream.setColor(Console.BLACK);
				stream.print(dateFormat.format(new java.util.Date())+" => ");
			}});
	}

	private synchronized void logExceptionWhithoutTime(Throwable e, boolean cause) {
		StringBuilder builder = new StringBuilder();
		if(cause)
			builder.append("Caused by: ");

		builder.append(e.getClass().getName()+": "+e.getMessage()+"\n");
		StackTraceElement[] traces = e.getStackTrace();
		for(int i=0 ; i<traces.length ; i++)
			builder.append("\t"+traces[i]+"\n");

		final String log = builder.toString();

		Display.getDefault().asyncExec(new Runnable() {
			public void run() {
				MessageConsoleStream stream = newMessageStream();
				stream.setColor(Console.GRAY);
				stream.print(log);
			}});

		if(e.getCause() != null)
			logExceptionWhithoutTime(e.getCause(), true);

	}
}
*/
